package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    //处理超时订单任务（每分钟）
    @Scheduled(cron = "0 * * * * ?")
    //@Scheduled(cron = "0/10 * * * * ?")//测试用
    public void processTimeoutOrder() {
        log.info("开始处理支付超时订单为取消");
        //先把超时支付订单获取
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);//15分之前的时间点
       /* List<Orders> ordersList = ordersMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        //把状态改为取消
        if (ordersList!=null && ordersList.size()>0) {
            //更新
            for (Orders order : ordersList) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("支付超时，自动取消");

                ordersMapper.update(order);
            }

        }*/

        // update orders set status=6 ,cancel_time= 当前时间 ,cancel_reason=取消的原因
        // where status = 1 and order_time <= 15min前的时间

        ordersMapper.autoCancelTimeoutOrder(LocalDateTime.now(),LocalDateTime.now().minusMinutes(15));

    }


    //处理派送中订单处理任务(每天的凌晨1点)
    @Scheduled(cron = "0 0 1 * * ?")//上线后使用
    //@Scheduled(cron = "0/20 * * * * ?")//测试用
    public void processDeliveryOrder() {
        log.info("开始处理派送中订单为完成");
        LocalDateTime time = LocalDateTime.now().minusHours(1);//凌晨00:00

        // update orders set status=5
        // where status = 4 and order_time <= 1h前的时间

        ordersMapper.autoCompleteDeliveryOrder(time);
    }

}
